package com.wfm.mianshi.多个线程打印ABCABC.利用线程池;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {

    static class PrintABC {
        private int state = 0;
        private static final int PRINT_TIMES = 3;
        private final ReentrantLock lock = new ReentrantLock();
        private final Condition conditionA = lock.newCondition();
        private final Condition conditionB = lock.newCondition();
        private final Condition conditionC = lock.newCondition();

        public void printA() {
            lock.lock();
            try {
                for (int i = 0; i < PRINT_TIMES; i++) {
                    while (state % 3 != 0) {
                        conditionA.await();
                    }
                    System.out.print("A");
                    state++;
                    conditionB.signal();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }

        public void printB() {
            lock.lock();
            try {
                for (int i = 0; i < PRINT_TIMES; i++) {
                    while (state % 3 != 1) {
                        conditionB.await();
                    }
                    System.out.print("B");
                    state++;
                    conditionC.signal();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }

        public void printC() {
            lock.lock();
            try {
                for (int i = 0; i < PRINT_TIMES; i++) {
                    while (state % 3 != 2) {
                        conditionC.await();
                    }
                    System.out.print("C");
                    state++;
                    conditionA.signal();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }
    }

        public static void main(String[] args) {
            PrintABC printABC = new PrintABC();
            ExecutorService executorService = Executors.newFixedThreadPool(3);

            executorService.submit(printABC::printA);
            executorService.submit(printABC::printB);
            executorService.submit(printABC::printC);

            executorService.shutdown();
        }
}
